package com.eulog.client.trump;

import java.util.ArrayList;

public class TrumpDecks {
	private ArrayList<TrumpCard> decks;
	private int deckSize;
	private int deckPivot; // if zero, no pivot
	private int currentPosition;	
	private final int ID;
	private static int lastID = 0;
	private int totalCardsNumber;
	
	// if deckPivot is zero, no pivot
	public TrumpDecks(int deckNum, boolean doShuffle, int pivot) {
		
		ID = lastID;
		lastID ++;
		
		decks = new ArrayList<TrumpCard>();
		initDeck(deckNum,doShuffle,pivot);
	}
	
	@Override
	public String toString() {
		String name = "";
		for (TrumpCard card : decks) {
			name += card + " ";
		}
		
		return name;
	}
	
	public int getID() {return ID;}
	
	public int getDeckSize() {return deckSize;}
	
	public int getTotalCards() {return totalCardsNumber;}
	
	public int getUsedCardsNumber() {return currentPosition;}
	
	public void initDeck(int deckNum, boolean doShuffle,int pivot) {
		currentPosition = 0;
		
		if(deckNum>0) {
			deckSize = deckNum;
			
			decks.clear();
			for(int i=0; i<deckSize; i++) {
				decks.addAll(TrumpCard.newDeck());
			}
			
			if(doShuffle) shuffle();
		}
		else
		{
			//throw error
		}
		
		deckPivot = pivot;
		
		totalCardsNumber = decks.size();
	}
	
	public boolean isCardAvailable(int n) {
		int pivot;
		if(deckPivot>0 && deckPivot < totalCardsNumber) pivot = deckPivot;
		else pivot = totalCardsNumber;
		
		if( (currentPosition+n) < pivot) return true;
		return false;
	}
	
	public void shuffle() {
		int size = decks.size();
		int rand;
		ArrayList<TrumpCard> tempdecks = new ArrayList<TrumpCard>();
		tempdecks.addAll(decks);
		decks.clear();
		
		for(int i=size-1; i>=0; i--) {
			rand=(int)java.lang.Math.floor(java.lang.Math.random()*i);
			decks.add(tempdecks.get(rand));
			tempdecks.remove(rand);
			
		}
	}
	
	public ArrayList<TrumpCard> deal(int n) {
		ArrayList<TrumpCard> handCard = new ArrayList<TrumpCard>();
		
		for(int i = 0; i < n; i++) {
			handCard.add(dealOneCard());
		}
		
		return handCard;
	}
	
	public TrumpCard dealOneCard() {
		TrumpCard card =decks.get(currentPosition);
		currentPosition++;
		return card;
	}


}
